<template>
  <div style="">
<!--    <h1>数据标准管理</h1>-->
    <!-- 查询表单 -->
    <div style="padding: 20px;">
      <a-form :form="searchParams" layout="inline">
        <!-- 查询表单项 -->
        <a-form-item label="标准名称">
          <a-input v-model="searchParams.standardName" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="fetchStandardList">查询</a-button>
        </a-form-item>
      </a-form>
    </div>
    <div style="text-align: right; margin: 10px;">
      <a-button type="primary" @click="handleEdit('add')">新增</a-button>&nbsp;&nbsp;
      <!--            <a-button type="danger" :loading="mergeLoading" @click="merge()">合并</a-button>-->
    </div>
    <a-table :columns="columns" :data-source="standardList" :pagination="false">
      <template slot="action" slot-scope="text, record">
        <a @click="handleEdit(record)">编辑</a>
        <a @click="handleDelete(record.id)">删除</a>
      </template>
    </a-table>
    <!-- 分页器 -->
    <a-pagination :show-total="total => `共${total}条`" :total="total" :current="pagination.current"
                  :pageSize="pagination.pageSize" @change="handlePaginationChange" />

    <a-modal :visible="isModalVisible" :title="modalTitle" @cancel="handleCancel">
      <a-form :form="formData" :label-col="{ span: 8 }" :wrapper-col="{ span: 12 }" @submit="handleSubmit">
        <a-form-item label="标准编码" name="standardCode">
          <a-input v-model="formData.standardCode" />
        </a-form-item>
        <a-form-item label="标准名称" name="standardName">
          <a-input v-model="formData.standardName" />
        </a-form-item>
        <a-form-item label="标准类型" name="standardType">
          <a-select v-model="formData.standardType">
            <a-select-option v-for="type in standardTypes" :key="type.value" :value="type.value">
              {{ type.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="标准值" name="standardValue">
          <a-input v-model="formData.standardValue" />
        </a-form-item>
        <a-form-item label="标准描述" name="standardDescription">
          <a-input v-model="formData.standardDescription" />
        </a-form-item>
      </a-form>
      <div slot="footer">
        <a-button type="primary" html-type="submit">确定</a-button>
        <a-button @click="handleCancel">取消</a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {commonPostAction, commonGetAction} from "@/api/esManage";

export default {
  data() {
    return {
      standardList: [],
      total: 0,
      searchParams: {
        standardName: ''
      },
      columns: [
        {
          title: '标准编码',
          dataIndex:'standardCode',
          key:'standardCode'
        },
        {
          title: '标准名称',
          dataIndex:'standardName',
          key:'standardName'
        },
        {
          title: '标准类型',
          dataIndex:'standardType',
          key:'standardType'
        },
        {
          title: '标准值',
          dataIndex:'standardValue',
          key:'standardValue'
        },
        {
          title: '操作',
          key: 'action',
          slots: { customRender: 'action' }
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10,
      },
      isModalVisible: false,
      modalTitle: '',
      formData: {
        standardCode: '',
        standardName: '',
        standardType: '',
        standardValue: '',
        standardDescription: ''
      },
      standardTypes: [
        { value: 'FIELD_TYPE', label: '字段类型标准' },
        { value: 'DATA_FORMAT', label: '数据格式标准' },
        { value: 'CODE_LIST', label: '代码集标准' },
        { value: 'BUSINESS_RULE', label: '业务规则标准' }
      ]
    };
  },
  methods: {
    async fetchStandardList() {
      try {
        let url = "/standard/list";
        commonGetAction(url).then(res => {
          this.standardList = res.data.result.records;
          this.total = parseInt(res.data.result.total);
        }).catch(err => {
          console.log(err)
        })
      } catch (error) {
        console.error('获取数据标准列表失败', error);
      }
    },
    handlePaginationChange(page, pageSize) {
      this.pagination.current = page
      this.pagination.pageSize = pageSize
      this.fetchStandardList()
    },
    handleEdit(record) {
      this.modalTitle = '编辑数据标准';
      this.formData = { ...record };
      this.isModalVisible = true;
    },
    handleDelete(id) {
      this.$confirm('确定删除该数据标准?', '提示', {
        okText: '确定',
        cancelText: '取消',
        type: 'warning'
      }).then(() => {
        try {
          let url = "/standard/"+id;
          commonGetAction(url).then(res => {
            this.$message.success('数据标准删除成功');
            this.fetchStandardList();
          })
        } catch (error) {
          console.error('删除数据标准失败', error);
          this.$message.error('删除失败，请重试');
        }
      });
    },
    handleSubmit() {
      try {
        if (this.modalTitle === '编辑数据标准') {
          try {
            let url = "/standard/update";
            commonPostAction(url, this.formData).then(res => {
              this.fetchStandardList();
            })
          } catch (error) {
            console.error('删除数据标准失败', error);
            this.$message.error('删除失败，请重试');
          }
        } else {
          try {
            let url = "/standard/create";
            commonPostAction(url, this.formData).then(res => {
              this.fetchStandardList();
            })
          } catch (error) {
            console.error('删除数据标准失败', error);
            this.$message.error('删除失败，请重试');
          }
        }
        this.updateRelatedFields();
        this.$message.success('操作成功');
        this.isModalVisible = false;
        this.fetchStandardList();
      } catch (error) {
        this.$message.error('操作失败');
        console.error('保存数据标准失败', error);
      }
    },
    updateRelatedFields() {
      try {
        // 获取关联该标准的字段
        let url = "/field/relatedByStandard/" + this.formData.id;
        commonGetAction(url).then(res => {
          const fields = res.data.data;
          // 批量更新字段
          for (const field of fields) {
            // 根据实际变更内容更新字段
            field.fieldType = this.formData.standardValue;
            commonPostAction('/field/update', field).then(res => {
            })
          }
        })
      } catch (error) {
        console.error('删除数据标准失败', error);
        this.$message.error('删除失败，请重试');
      }
    },
    handleCancel() {
      this.isModalVisible = false;
      this.formData = {};
    }
  },
  mounted() {
    this.fetchStandardList();
  }
};
</script>